package com.feib.stms.model;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;



public class CalendarDTO {
	/**
	 * 年
	 */
	private Integer year;
	
	/**
	 * 月
	 */
	private Integer month;
	
	/**
	 * 日期 
	 */
	private Calendar workCal;
	
	/**
	 * 從資料庫查詢出來的
	 */
	private List<BusinessDay> list;
	
	public CalendarDTO(Integer year, Integer month , List<BusinessDay> list) {
		super();
		this.year = year;
		this.month = month;
		this.list = list;
		workCal = Calendar.getInstance();
		workCal.set(year, month, 1);
	}
	
	/**
	 * 獲取行事歷列表
	 * @return
	 */
	public List<List<BusinessDay>> getWeekList(){
		List<List<BusinessDay>> weekList = new ArrayList<List<BusinessDay>>();
		List<BusinessDay> week = null;
		int j=0;
		for (int i = 1; i <= workCal.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {//循環當前月的所有天數
			BusinessDay day = null;
			if(list != null && list.size() > 0){//資料庫有資料
				day = list.get(i - 1);//取得每一天
				SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd");
				String tempDate = sf.format(day.getTheDate());
				String temp = tempDate.substring(tempDate.lastIndexOf("/") + 1);
				Calendar oneDay = getDay(workCal ,Integer.parseInt(temp));
				day.setOneDay(oneDay);
				if(day.getStatus().equals("W")){
					day.setCheck("checked");
				}
			}else{//資料庫無資料
				Calendar oneDay = getDay(workCal ,i);//取得每一天
				day = new BusinessDay();
				day.setOneDay(oneDay);
			}
			
			if(j == 8 || i == 1){
				if(week != null){
					weekList.add(week);
				}
				j=1;
				week = new ArrayList<BusinessDay>();
			}
			while(j<8){
				if(getDayOfWeek(day.getOneDay()) == j){
					day.setDay(i);
					week.add(day);
					j++;
					break;
				} else {
					week.add(new BusinessDay());
					j++;
				}
			}
		}
		weekList.add(week);
		return weekList;
	}
	
	/**
	 *  獲得該日為一周中的第幾天
	 * @param cal
	 * @return
	 */
	public Integer getDayOfWeek(Calendar cal){
		return cal.get(Calendar.DAY_OF_WEEK);
	}
	
	/**
	 * 獲得某月中的日期(天)
	 * @param ca
	 * @param day
	 * @return
	 */
	private Calendar getDay(Calendar ca ,int day){
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR, ca.get(Calendar.YEAR));
		cal.set(Calendar.MONTH, ca.get(Calendar.MONTH));
		cal.set(Calendar.DAY_OF_MONTH, day);
		return cal;
	}

	/**
	 * @return month
	 */
	public Integer getMonth() {
		return month;
	}

	/**
	 * @param month 的設定的 month
	 */
	public void setMonth(Integer month) {
		this.month = month;
	}

	/**
	 * @return workCal
	 */
	public Calendar getWorkCal() {
		return workCal;
	}

	/**
	 * @param workCal 的設定的 workCal
	 */
	public void setWorkCal(Calendar workCal) {
		this.workCal = workCal;
	}

	/**
	 * @return year
	 */
	public Integer getYear() {
		return year;
	}

	/**
	 * @param year 的設定的 year
	 */
	public void setYear(Integer year) {
		this.year = year;
	}
	
	
}
